#!/usr/bin/env bash
#######################################
tips_of_umount_chroot_container_02() {
	cat <<-EOF
		${YELLOW}Q:为什么卸载chroot容器需要如此谨慎？${RESET}
		A:此处引用umount的用户手册。
		${GREEN}Note that a filesystem cannot be unmounted when it is 'busy' - for example, when there are open files on it, or when some process
		       has its working directory there, or when a swap file on it is in use.  The offending process could even be  umount  itself  -  it
		       opens  libc,  and  libc  in its turn may open for example locale files.  A lazy unmount avoids this problem, but it may introduce
		       other issues.${RESET}
		在上文中介绍到了${BLUE}--lazy${RESET}参数，然而这并不是重点。
		重点是mount后的目录，在umount时可能会遇到一些问题。
		当设备处于繁忙状态时，将无法卸载。即便使用强制卸载，也依旧（可能）存在一些问题。 
		这和windows的外置USB设备无法弹出时，手动拔出是不一样的。
		chroot挂载了系统底层的目录,为了保证系统不受损害，当检测到无法卸载时，您可通过手动重启设备来解决。
		本工具提供了检测功能，当检测到挂载目录为空时将会出现${GREEN}total 0${RESET}。
		在这种情况下，一般能正常卸载。
		但也存在特例，当您使用套娃循环挂载，不断地挂载自身时，将有可能导致异常现象。
		为防止异常状况，本工具提供了多次检测的功能。
		当检测到mounted的目录不为空时,将无法继续执行操作。
		因此在一般情况下，您都可以安心卸载容器。
		欲了解更多关于mount和umount的内容，请阅览相关手册。
		In order to prevent accidental deletion of directories, tmoe-linux manager have done additional detection steps.
		So you can safely remove the ${BLUE}${DEBIAN_FOLDER}${RESET} container under normal circumstances.
		If you find that some directories cannot be unmounted, you can solve it by restarting the device.
	EOF
}
##############
tips_of_umount_chroot_container_01() {
	cat <<-EOF
		移除容器前，请先确保您unmounted了容器mounted目录。
		建议您在移除前进行备份，若因操作不当而导致数据丢失，开发者${RED}概不负责${RESET}！！！
		Before removing the container, make sure you have unmounted ${BLUE}dev dev/shm dev/pts proc sys root/sd media/sd media/tf${RESET} and other directories.
		It is recommended that you backup the entire system before removal. 
		If the data is lost due to improper operation, the developer is not responsible! 
	EOF
}
###########
remove_gnu_linux_container() {
	case ${TMOE_CHROOT} in
	true)
		tips_of_umount_chroot_container_01
		#source ${TMOE_SHARE_DIR}/removal/umount &>/dev/null
		tips_of_umount_chroot_container_02
		;;
	esac
	if [ "$(ls ${DEBIAN_CHROOT}/proc 2>/dev/null)" ]; then
		printf "%s\n" "检测到proc目录不为空，无法继续卸载"
		printf "%s\n" "Please restart the device to unmount the ${DEBIAN_CHROOT}/${i} directory."
		printf "为防止目录被清空，请退出！！！"
		press_enter_to_return
		exit 1
	fi

	cd ${HOME}
	for i in dev/shm dev/pts proc sys storage/emulated/0/* media/sd media/tf; do
		if [ -e "${DEBIAN_CHROOT}/${i}" ]; then
			ls -lAh "${DEBIAN_CHROOT}/${i}" 2>/dev/null
		fi
	done
	unset i
	check_rootfs_dir
	grep ${DEBIAN_CHROOT} /proc/mounts
	pkill -9 proot 2>/dev/null
	pkill -9 chroot 2>/dev/null
	ps -e | grep proot
	ps -e | grep startvnc
	printf "%s\n" "移除容器前，本工具将${RED}自动停止${RESET}${BLUE}${DEBIAN_FOLDER}${RESET}容器所运行的${GREEN}所有进程${RESET}。"
	printf "%s\n" "Tmoe-linux manager will ${RED}automatically stop${RESET} ${GREEN}all processes${RESET} running in the ${BLUE}${DEBIAN_FOLDER}${RESET} container, and unmount the container directory."
	pgrep proot &>/dev/null
	if [ "$?" = "0" ]; then
		printf '%s\n' '检测到proot容器正在运行，请先输stopvnc或手动强制停止容器运行'
		#printf "%s\n" "若${ROOTFS_NAME}容器未停止运行，则建议你先手动在容器中执行stopvnc，再进行移除操作。"
	fi
	ls -l ${DEBIAN_CHROOT}/media/termux/* 2>/dev/null
	if [ "$?" = "0" ]; then
		printf '%s\n' 'WARNING！检测到/media/termux无法强制卸载，您当前使用的可能是chroot容器'
		printf "%s\n" "若为误报，则请先停止容器进程，再手动移除${DEBIAN_CHROOT}/media/sd"
		printf '%s\n' '建议您在移除前进行备份，若因操作不当而导致数据丢失，开发者概不负责！！！'
	fi
	printf "%s\n" "Detecting container size... 正在检测${ROOTFS_NAME}容器占用空间大小"
	${TMOE_PREFIX} du -sh ${DEBIAN_CHROOT} --exclude=${DEBIAN_CHROOT}/media/tf --exclude=${DEBIAN_CHROOT}/media/sd --exclude=${DEBIAN_CHROOT}/media/termux 2>/dev/null
	if [ ! -d ${DEBIAN_CHROOT} ]; then
		printf "%s\n" "${YELLOW}It is detected that you do not currently have GNU/Linux container installed. 检测到您当前未安装容器${RESET}"
	fi
	printf "%s\n" "Press ${GREEN}enter${RESET} to ${RED}remove${RESET}."
	printf "%s\n" "按${GREEN}回车键${RESET}确认${RED}移除${RESET}"
	printf "%s\n" "Do you want to remove it?${PURPLE}[Y/n]${RESET}"
	read -r opt
	case $opt in
	y* | Y* | "")
		#non-rm "${CONFIG_FOLDER}/chroot_container"
		case ${TMOE_CHROOT} in
		true)
			sudo rm -rfv ${PREFIX}/bin/debian-rm ${PREFIX}/bin/code ~/.config/tmoe-linux/across_architecture_container.txt "${DEBIAN_CHROOT}"
			sudo chmod 777 -Rv ${DEBIAN_CHROOT}
			;;
		*)
			rm -rfv ${PREFIX}/bin/debian-rm ${PREFIX}/bin/code ~/.config/tmoe-linux/across_architecture_container.txt "${DEBIAN_CHROOT}"
			for i in ${PREFIX}/bin/debian-rm ${PREFIX}/bin/code ~/.config/tmoe-linux/across_architecture_container.txt; do
				[[ ! -e ${i} ]] || sudo rm -rfv ${i}
			done
			chmod 777 -Rv ${DEBIAN_CHROOT} || sudo chmod 777 -Rv ${DEBIAN_CHROOT}
			;;
		esac
		rm -rfv "${DEBIAN_CHROOT}" || sudo rm -rfv "${DEBIAN_CHROOT}"
		printf "%s\n" "如需删除（通用的）启动脚本，则请手动输${RED}rm -fv ${BLUE}${PREFIX}/bin/debian ${PREFIX}/bin/novnc ${PREFIX}/bin/debian-i ${PREFIX}/bin/tmoe ${PREFIX}/bin/startvnc ${PREFIX}/bin/startx11vnc ${PREFIX}/bin/stopvnc ${PREFIX}/bin/startxsdl${RESET}"
		sed -i '/alias debian=/d ; /alias debian-rm=/d' ${PREFIX}/etc/profile 2>/dev/null
		source profile >/dev/null 2>&1
		#printf '%s\n' 'The container has been removed. If you want to uninstall aria2, enter "apt remove aria2" or "apt purge aria2"'
		#printf '%s\n' '移除完成，如需卸载aria2,请手动输apt remove aria2'
		printf "%s\n" "Deleted已删除"
		;;
	n* | N*) printf "%s\n" "skipped." ;;
	*) printf "%s\n" "Invalid choice. skipped." ;;
	esac
	#printf "%s\n" "若需删除tmoe-linux管理器，则请输rm -f ${PREFIX}/bin/debian-i"
	printf '%s\n' 'If you want to reinstall, it is not recommended to remove the image file.'
	printf "%s\n" "${YELLOW}若您需要重装容器，则不建议删除镜像文件。${RESET} "
	cd ${ROOTFS_DIR}
	DISTRO_ROOTFS_NAME=$(printf "%s\n" "${ROOTFS_NAME}" | cut -d '-' -f 1)
	#${ROOTFS_NAME}*-rootfs.tar.*
	ls -lh ${DISTRO_ROOTFS_NAME}*${ARCH_TYPE}*-rootfs.tar.* 2>/dev/null
	printf "%s\n" "${YELLOW}请问您是否需要删除${BLUE}容器镜像文件？${PURPLE}[Y/n]${RESET} "
	printf "%s\n" "${RED}rm -fv ${BLUE}${DISTRO_ROOTFS_NAME}*${ARCH_TYPE}*-rootfs.tar.*${RESET}"
	printf "%s\n" "Do you need to delete the image file (${BLUE}${DISTRO_ROOTFS_NAME}*${ARCH_TYPE}*-rootfs.tar.*${RESET})?${PURPLE}[Y/n]${RESET}"
	read -r opt
	case $opt in
	y* | Y* | "")
		#rm -fv ${DEBIAN_CHROOT}*-rootfs.tar.*
		#此处应删除ROOTFS_NAME而非DEBIAN_FOLDER开头的rootfs文件
		rm -fv ${ROOTFS_DIR}/${DISTRO_ROOTFS_NAME}*${ARCH_TYPE}*-rootfs.tar.*
		printf "%s\n" "Deleted已删除"
		;;
	n* | N*) printf "%s\n" "${YELLOW}Skipped,已跳过，按回车键返回。${RESET} " ;;
	*) printf "%s\n" "${YELLOW}Invalid choice，skipped.已跳过，按回车键返回。${RESET} " ;;
	esac
	#tmoe_manager_main_menu
}
###################
remove_gnu_linux_container
